#include <pthread.h>
#include <unistd.h>
#include <iostream>

using std::cout;
using std::endl;

pthread_mutex_t mutex;
pthread_cond_t cond;

void * threadfunc(void * arg)
{
    sleep(3);
    //通知等待条件变量的线程
    pthread_cond_broadcast(&cond);

    return NULL;
}

void * threadfunc2(void * arg)
{
    cout << "sub thread 2 is running" << endl;
    pthread_mutex_lock(&mutex);
    pthread_cond_wait(&cond, &mutex);

    cout << "sub thread 2 wake up" << endl;
    pthread_mutex_unlock(&mutex);

    return NULL;
}

int main()
{
    pthread_t pthid, pthid2;
    pthread_create(&pthid, NULL, threadfunc, NULL);
    pthread_create(&pthid2, NULL, threadfunc2, NULL);

    //动态初始化
    pthread_mutex_init(&mutex, NULL);
    pthread_cond_init(&cond, NULL);
    cout << "111" << endl;

    pthread_mutex_lock(&mutex);

    pthread_cond_wait(&cond, &mutex);
    //当main线程中wait函数返回以后，就加锁成功了,继续往下执行
    cout << "main thread wake up" << endl;
    
    pthread_mutex_unlock(&mutex);

    //等待子线程执行完毕
    pthread_join(pthid, NULL);
    pthread_join(pthid2, NULL);

    pthread_mutex_destroy(&mutex);
    pthread_cond_destroy(&cond);
    return 0;
}

